
#include <stdio.h>
#include "wm_hal.h"
#include <assert.h>

void Error_Handler(void);
HAL_StatusTypeDef Avoid_Copy_Firm(uint32_t addr);
void DumpBuffer(char *name, uint8_t *buffer, uint32_t len);

int main(void)
{
	SystemClock_Config(CPU_CLK_160M);
	printf("enter main\r\n");
	Avoid_Copy_Firm(0x800F000);

	while (1)
	{
		printf(".");
		HAL_Delay(1000);
	}
}

HAL_StatusTypeDef Avoid_Copy_Firm(uint32_t addr)
{
	uint8_t aeskey[] = {0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 
						0x38, 0x39, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66};
						
	uint8_t uid[18];
	uint8_t *buf = malloc(128);
	psCipherContext_t ctx;
	HAL_StatusTypeDef ret = HAL_OK;
	
	HAL_FLASH_Read_Unique_ID(uid);
	DumpBuffer("uid", uid, 18);
	
	HAL_FLASH_Read(addr, buf, 32);
	HAL_CRYPTO_AES_Init(&ctx, NULL, aeskey, 16, CRYPTO_MODE_ECB);
	HAL_CRYPTO_AES_Encrypt_Decrypt(&ctx, buf, buf, 32, CRYPTO_WAY_DECRYPT);
	DumpBuffer("decrypted uid", buf, 32);
	
	if((memcmp(uid, buf, 9) != 0) || (memcmp(&uid[9], &buf[16], 9) != 0))
	{
		printf("%s failed\r\n", __func__);
		assert(0);							// FLASH UNIQUE ID匹配失败，停止程序运行
	}
	else
	{
		printf("%s success\r\n", __func__);
	}
	free(buf);
	return ret;
}

void DumpBuffer(char *name, uint8_t *buffer, uint32_t len)
{
	int i = 0;
	
	printf("%s:\r\n", name);
	for (i = 0; i < len; i++)
	{
		if ((i%16) == 0)
		{
			printf("\r\n");
		}
		printf("%02X ", buffer[i]);
	}
	printf("\r\n");
}

void Error_Handler(void)
{
	while (1)
	{
	}
}

void assert_failed(uint8_t *file, uint32_t line)
{
	printf("Wrong parameters value: file %s on line %d\r\n", file, line);
}